package spring.cloud.tasks.executor.executor.task.execute_statistics;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.executor.Executor;
import spring.cloud.tasks.executor.executor.task.TaskExecutor;

import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 执行器任务统计信息清零
 */
@Slf4j
@Setter
@Getter
public class ExecuteStatisticsResetTask extends TimerTask {
    private String executorId;
    private Executor executor;

    public ExecuteStatisticsResetTask(String executorId) {
        this.executorId = executorId;
        this.executor = null;
    }

    @Override
    public void run() {
        try {
            ConcurrentHashMap<String, TaskExecutor> taskIdToTaskExecutorMap = this.executor.taskIdToTaskExecutorMap.getTaskIdToTaskExecutorMap();
            if (taskIdToTaskExecutorMap == null) {
                return;
            }
            Iterator<Map.Entry<String, TaskExecutor>> iterator = taskIdToTaskExecutorMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, TaskExecutor> next = iterator.next();
                String taskId = next.getKey();
                TaskExecutor taskExecutor = next.getValue();
                // 清零内存统计值
                ExecuteStatistics.resetSuccessFailureCount(taskId);
                // 清零zk统计值
                taskExecutor.getTaskExecutorInfoService().persistProcessFailureCount(0);
                taskExecutor.getTaskExecutorInfoService().persistProcessSuccessCount(0);
                log.info("执行器" + executorId + "清理任务" + taskId + "统计信息成功");
            }
        } catch (Throwable t) {
            log.error("清理任务统计信息失败", t);
        }
    }
}
